<script lang="ts">
	import { onMount } from 'svelte';
	import type { Option } from '$lib/components/Basic/Popover/types';
	import PopoverCascader from '$lib/components/Basic/Popover/PopoverCascader.svelte';
	import { debounce } from 'lodash-es';
	import { goto } from '$app/navigation';
	// 组件属性
	export let menuItems: Option[] = [];
	export let label: string = 'label';

	// 状态管理
	let isOpen: boolean = false;
	let activeMenuIndex: number | null = null;
	let containerRef: HTMLElement;
	let triggerRefs: HTMLElement[] = [];
	let triggerRects = [{ top: 0, left: 0, bottom: 0, right: 0, width: 0, height: 0 }];
	let overTriggerRef: HTMLElement;
	let overTriggerRect = { top: 0, left: 0, bottom: 0, right: 0, width: 0, height: 0 };
	let totalWidth: number = 0;
	let visibleCount: number = 0;
	const overflowButtonWidth: number = 50;
	let offsetWidth: number = 0;
	let overflowItems: Option[] = [];

	// 显示子菜单
	const showSubmenu = (index: number, event: MouseEvent | KeyboardEvent) => {
		if (isOpen) {
			activeMenuIndex = index;
		}
	};

	// 隐藏子菜单
	const hideSubmenu = () => {
		isOpen = false;
		activeMenuIndex = null;
	};

	//
	const clickMenu = (option:Option) => {		
		if(option.code && option.code!=null && option.code!=undefined){
			goto(option.code)
		}else{
			goto('/home')
		}
	};

	//计算可见项
	const calculateVisible = () => {
		if (containerRef && menuItems.length > 0 && triggerRects.length > 0) {
			const containerRect = containerRef.getBoundingClientRect();
			const containerWidth = containerRect.width;
			overflowItems.length = 0;
			if (totalWidth <= containerWidth) {
				visibleCount = triggerRects.length;
				offsetWidth = 0;
				return visibleCount;
			}
			const availableWidth = containerWidth - overflowButtonWidth;
			let visibleWidth = 0;
			visibleCount = 0;
			// 计算能完整显示的菜单项数量
			for (let i = 0; i < triggerRects.length; i++) {
				visibleWidth = triggerRects[i].width + visibleWidth;
				if (visibleWidth > availableWidth) {
					overflowItems.push(menuItems[i]);
				} else {
					visibleCount++;
				}
			}
		}
		overTriggerRect = {
			top: triggerRects[visibleCount].top,
			left: triggerRects[visibleCount].left,
			bottom: triggerRects[visibleCount].bottom,
			right: triggerRects[visibleCount].left + overflowButtonWidth,
			width: overflowButtonWidth,
			height: triggerRects[visibleCount].height
		};
		offsetWidth = triggerRects[visibleCount].left - triggerRects[triggerRects.length - 1].right;		
		return visibleCount;
	};

	/**
	 * 处理窗口大小变化
	 */
	const handleResize = debounce(() => {		
		calculateVisible();
	}, 200);
	
	onMount(() => {
		if (triggerRefs && triggerRefs.length > 0) {
			triggerRefs.forEach((el, index) => {
				if (el) {
					const rect = el.getBoundingClientRect();
					totalWidth = totalWidth + rect.width;
					triggerRects[index] = {
						top: rect.top,
						left: rect.left,
						bottom: rect.bottom,
						right: rect.right,
						width: rect.width,
						height: rect.height
					};					
				}
			});
		}
		calculateVisible();
		window.addEventListener('resize', handleResize);			
		// 组件卸载时清理事件监听
		return () => {
			// document.removeEventListener('click', handleClickOutside);
			window.removeEventListener('resize', handleResize);			
		};
	});
</script>

<div class="menu-container" bind:this={containerRef}>
	{#each menuItems as menuItem, index (index)}
		<div
			bind:this={triggerRefs[index]}
			class="menu-item hover-bg"
			class:isActive={activeMenuIndex != null &&
				activeMenuIndex == index &&
				menuItem.children &&
				menuItem.children.length > 0}
			class:isHide={index > visibleCount - 1}
			on:click={(e) => {
				isOpen = true;
				showSubmenu(index, e);
			}}
			on:keydown={() => {}}
			on:mouseenter={(e) => {
				showSubmenu(index, e);
			}}
			role="menuitem"
			tabindex="0"
		>
			{menuItem[label]}
		</div>
		{#if activeMenuIndex != null && activeMenuIndex == index && menuItem.children && menuItem.children.length > 0}
			<PopoverCascader
				bind:triggerRef={triggerRefs[index]}
				{label}
				options={menuItem.children}
				onClose={hideSubmenu}
				onChange={clickMenu}
			></PopoverCascader>
		{/if}
	{/each}
	<div
		bind:this={overTriggerRef}
		class="menu-item hover-bg"
		class:isActive={activeMenuIndex != null && activeMenuIndex == menuItems.length}
		class:isHide={menuItems.length <= visibleCount}
		style={`transform: translateX(${offsetWidth}px);width: ${overflowButtonWidth}px`}
		on:mouseenter={(e) => {
			activeMenuIndex = menuItems.length;
		}}
		role="menuitem"
		tabindex="0"
	>
		···
	</div>
	{#if activeMenuIndex != null && activeMenuIndex == menuItems.length}
		<PopoverCascader
			bind:triggerRef={overTriggerRef}
			{label}
			options={overflowItems}
			onClose={hideSubmenu}
			onChange={clickMenu}
		></PopoverCascader>
	{/if}
</div>

<style scoped lang="scss">
	.menu-container {
		padding: 1px;
		height: 32px;
		display: flex;
		flex-wrap: nowrap;
		overflow: hidden;
		position: relative;
		.menu-item {
			display: flex;
			align-items: center;
			justify-content: center;
			padding: 0 16px;
			white-space: nowrap;			
			cursor: pointer;
			border-radius: var(--border-radius);
			/* 关键：禁用收缩，固定宽度生效 */
			flex-shrink: 0;
			&.isHide {
				visibility: hidden;
			}
		}
	}
</style>
